<?php

class PanelController extends Zend_Controller_Action {

	const MESSAGE_TYPE_SUCCESS = 'success';
	
	const MESSAGE_ACCESS_DENIED = 'Brak dostpu.';
	const MESSAGE_SAVE_SUCCESS = 'Dane zostay poprawnie zapisane.';
	const MESSAGE_TO_ACCEPT_SUCCESS = 'Dane aplikacje została wysłana do akceptacji.';
	
	/**
	 * 
	 * @var Zend_Session_Namespace
	 */
	private $session;
	
	public function init() {
		$this->_helper->layout->setLayout('noBBLayout');
		$this->session = new Zend_Session_Namespace(Core_Core::getInstance()->getConfigs()->session->namespacePanel);
		if (!$this->isLogged()) {
			$this->_forward('login');
			return;
		}
		if ($this->getRequest()->isXmlHttpRequest()) {
			$this->_helper->layout()->disableLayout();
		}
	}

	public function loginAction() {
		if ($this->getRequest()->getParam('logout', null) == 1)
			$this->logout();
		if ($this->isLogged()) {
			$this->_redirect($this->view->url(
       	array('action' => 'logged'), null, true
      ));
		}
		$this->view->error = false;
		$this->view->appId = 'TEST01';
		$this->view->appKey = '123456';
		if ($this->getRequest()->getParam('doLogin', null) !== null) {
			$application = ApplicationsQuery::create()
				->filterByAppId($this->getRequest()->getParam('appId', null))
				->filterByAdminKey($this->getRequest()->getParam('appKey', null))
				->findOne();
			if (!$application instanceof Applications) {
				$this->view->error = true;
				$this->view->appId = $this->getRequest()->getParam('appId');
				$this->view->appKey = $this->getRequest()->getParam('appKey');
				$this->session->appId = null;
			}
			else {
				$this->session->appId = $application->getId();
				$this->_redirect($this->view->url(
        	array('action' => 'logged'), null, true
        ));
			}
		}
	}
	
	public function loggedAction() {
		$application = ApplicationsQuery::create()->findOneById($this->session->appId);
		
		if (!$application instanceof Applications) {
			$this->render('errors/applicationNotFound');
			$this->logout();
			return;
		}
		
		$applicationSets = ApplicationDataSetsQuery::create()
		->filterByStatus(array(ApplicationDataSets::STATUS_ACCEPTED, ApplicationDataSets::STATUS_EDITABLE, ApplicationDataSets::STATUS_TO_ACCEPT))
		->filterByApplicationId($application->getId())
		->leftJoinApplicationDataDefs()
		->find();
		
		$appEditable = null;
		$appAccepted = null;
		$this->view->appWaiting = false;
		if ($applicationSets->count() > 0) {
			foreach ($applicationSets as $applicationSet) {
				if ($applicationSet->getStatus() == ApplicationDataSets::STATUS_EDITABLE)
					$appEditable = $applicationSet;
				else if ($applicationSet->getStatus() == ApplicationDataSets::STATUS_ACCEPTED)
					$appAccepted = $applicationSet;
				else if ($applicationSet->getStatus() == ApplicationDataSets::STATUS_TO_ACCEPT)
					$this->view->appWaiting = true;
			}
		}
		
		$this->view->app = $application;
		$this->view->appEditable = $appEditable;
		$this->view->appAccepted = $appAccepted;
	}
	
	public function saveApplicationSetAction($toAccept=false) {		
		$this->jsonData();
		$data = $this->getRequest()->getParams();
		$application = ApplicationsQuery::create()->filterByToModified(1)->findOneById($this->session->appId);
		if (!$application instanceof Applications) {
			$this->view->status = false;
			$this->view->message = self::MESSAGE_ACCESS_DENIED;
			$this->view->messageType = Core_Exception_App::TYPE_INFO;
			return;
		}
		$applicationDataSet = ApplicationDataSetsQuery::create()
		->filterByApplicationId($this->session->appId)
		->filterByStatus(ApplicationDataSets::STATUS_EDITABLE)
		->findOne();
		
		$con = Propel::getConnection();
		$con->beginTransaction();
		try {
			if (!$applicationDataSet instanceof ApplicationDataSets) {
				$applicationDataSet = new ApplicationDataSets();
				$applicationDataSet->setApplicationId($this->session->appId);
				$applicationDataSet->setStatus(ApplicationDataSets::STATUS_EDITABLE);
			} else {
				ApplicationDataDefsQuery::create()
				->filterByApplicationDataSets($applicationDataSet)
				->delete($con);
			}
			if ($toAccept) {
				$application->setToModified(0);
				$application->save($con);
				$applicationDataSet->setStatus(ApplicationDataSets::STATUS_TO_ACCEPT);
			}
			$applicationDataSet->setName($this->getRequest()->getParam('name', null));
			$applicationDataSet->setNameEn($this->getRequest()->getParam('nameEn', null));
			$applicationDataSet->setDescription($this->getRequest()->getParam('description', null));
			$applicationDataSet->setDescriptionEn($this->getRequest()->getParam('descriptionEn', null));
			foreach ($this->getRequest()->getParam('info', array()) as $info) {
				$infoObj = new Core_Array($info, false);
				if ($infoObj->code == '' || $infoObj->code == null)
					throw new Core_Exception_App(6000);
				if (!in_array($infoObj->type, ApplicationDataDefs::$VALUE_TYPES))
					throw new Core_Exception_App(6001, array($infoObj->type));
				$applicationDataDef = new ApplicationDataDefs();
				$applicationDataDef->setCode($infoObj->code);
				$applicationDataDef->setLabel(($infoObj->label == '') ? null : $infoObj->label);
				$applicationDataDef->setLabelEn(($infoObj->labelEn == '') ? null : $infoObj->labelEn);
				$applicationDataDef->setDescription(($infoObj->desc == '') ? null : $infoObj->desc);
				$applicationDataDef->setDescriptionEn(($infoObj->descEn == '') ? null : $infoObj->descEn);
				$applicationDataDef->setDefaultValue(($infoObj->default == '') ? null : $infoObj->default);
				$applicationDataDef->setValueType($infoObj->type);
				$applicationDataDef->setType(ApplicationDataDefs::TYPE_INFO);
				$applicationDataSet->addApplicationDataDefs($applicationDataDef);
			}
			foreach ($this->getRequest()->getParam('link', array()) as $link) {
				$linkObj = new Core_Array($link, false);
				if ($linkObj->code == '' || $linkObj->code == null)
					throw new Core_Exception_App(6000);
				$applicationDataDef = new ApplicationDataDefs();
				$applicationDataDef->setCode($linkObj->code);
				$applicationDataDef->setLabel(($linkObj->label == '') ? null : $linkObj->label);
				$applicationDataDef->setLabelEn(($linkObj->labelEn == '') ? null : $linkObj->labelEn);
				$applicationDataDef->setDescription(($linkObj->desc == '') ? null : $linkObj->desc);
				$applicationDataDef->setDescriptionEn(($linkObj->descEn == '') ? null : $linkObj->descEn);
				$applicationDataDef->setDefaultValue(($linkObj->default == '') ? null : $linkObj->default);
				$applicationDataDef->setValueType(ApplicationDataDefs::VALUE_TYPE_STRING);
				$applicationDataDef->setType(ApplicationDataDefs::TYPE_LINK);
				$applicationDataSet->addApplicationDataDefs($applicationDataDef);
			}
			$applicationDataSet->save($con);
			$con->commit();
		} catch (Core_Exception_App $e) {
			$con->rollBack();
			$this->view->status = false;
			$this->view->message = $e->getUserMessage();
			$this->view->messageType = $e->getType();
			return;
		}
		$this->view->status = true;
		$this->view->message = self::MESSAGE_SAVE_SUCCESS;
		$this->view->messageType = self::MESSAGE_TYPE_SUCCESS;
	}
	
	public function acceptApplicationSetAction() {
		$this->saveApplicationSetAction(true);
		if (!$this->view->status) {
			return;
		}
		$this->view->message = self::MESSAGE_TO_ACCEPT_SUCCESS;
	}
	
	private function isLogged() {
		return ($this->session->appId != null );
	}
	
	private function logout() {
		$this->session->appId = null;
	}
	
	private function jsonData() {
		$this->_helper->viewRenderer->setNoRender(true);
		$action = $this->getRequest()->getActionName();
		$this->_helper->contextSwitch()
			->addActionContext($action, 'json')
			->setAutoJsonSerialization(true)
			->initContext('json');
		$this->getRequest()->setParam('format', 'json');
	}

}